import datetime
import json
import os
import traceback

from django.conf import settings
from django.core.paginator import Paginator
from django.db.models import Q
from django.http import JsonResponse
from django.utils.decorators import method_decorator
from rest_framework.pagination import PageNumberPagination
from rest_framework.response import Response
from rest_framework.decorators import APIView

from pets import models
from pets.api.serializer import PetTypeSerializer
from tools.decorators import get_request_ip
from tools.pages import Mypage
from tools.tool import get_time_to_file_name, get_file_type


@method_decorator(get_request_ip, name='dispatch')
class PetType(APIView):
    def get(self, request, *args, **kwargs):
        li = []
        resp = {"code": 0, "data": li}
        try:
            # 1.狗    2.猫
            body = request.query_params.dict()
            items = models.PetType.objects.filter().order_by('id')
            total = items.count()
            page = Mypage()
            page_list = page.paginate_queryset(items, request, view=self)
            ser = PetTypeSerializer(page_list, many=True)
            resp = {"code": 1, "data": ser.data, 'total': total}
        except Exception as e:
            print(traceback.format_exc())
        return Response(resp)

    def post(self, request, *args, **kwargs):
        li = []
        resp = {"code": 0, "data": li}
        try:
            body = request.data
            ser = PetTypeSerializer(data=body)
            if ser.is_valid():
                ser.save()
                resp = {"code": 1, "data": ser.data}
        except Exception as e:
            print(traceback.format_exc())
        return Response(resp)

    def put(self, request, *args, **kwargs):
        li = []
        resp = {"code": 0, "data": li}
        try:
            body = request.data
            id = body.get('id')
            item = models.PetType.objects.get(id=id)
            ser = PetTypeSerializer(instance=item, data=body)
            if ser.is_valid():
                ser.save()
                resp = {"code": 1, "data": ser.data}
        except Exception as e:
            print(traceback.format_exc())
        return Response(resp)

    def delete(self, request, *args, **kwargs):
        li = []
        resp = {"code": 0, "data": li}
        try:
            body = request.data
            id = body.get('id')
            models.PetType.objects.filter(id__in=id).delete()
            resp = {"code": 1, "data": li}
        except Exception as e:
            print(traceback.format_exc())
        return Response(resp)




